package com.comunity_cloud.client.model;

import java.io.Serializable;
import java.util.Collections;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.TreeMap;

import com.user_hosted_storage.dto.CommunityDTO;
import com.user_hosted_storage.dto.CommunityMemberDTO;

public class CommunityFile implements Serializable{

	/**
	 *  
	 */
	private static final long serialVersionUID = -2697376649865944338L;
	
	public enum State {
		PENDING,
		IN_PROGRESS,
		SYNCHRONIZED,
		DELETED
	}
	
	private String path;
	
	private byte[] image;
	
	private State state;

	private CommunityDTO community;
	
	private int progress;
	
	private long length;
	
	private String typeDesc;
	
	private Map<Long, Chunk> chunks = Collections.synchronizedMap(new TreeMap<Long, Chunk>());
	
	public static class Chunk {
		public long totalOffset;
		public CommunityMemberDTO primaryHost;
		public CommunityMemberDTO redundantHost;
		public long chunkSize;
	}
	
	public CommunityFile(CommunityDTO community) {
		this.community = community;
	}


	public State getState() {
		return state;
	}

	public void setState(State state) {
		this.state = state;
	}

	public CommunityDTO getCommunity() {
		return community;
	}
	
	public void setCommunity(CommunityDTO community) {
		this.community = community;
	}
	
	public int getProgress() {
		return progress;
	}
	
	public void setProgress(int progress) {
		this.progress = progress;
	}
	
	public long getLength() {
		return length;
	}
	
	public void setLength(long length) {
		this.length = length;
	}
	
	public void setTypeDesc(String typeDesc) {
		this.typeDesc = typeDesc;
	}
	
	public String getTypeDesc() {
		return typeDesc;
	}
	
	public String getPath() {
		return path;
	}


	public void setPath(String path) {
		this.path = path;
	}


	public byte[] getImage() {
		return image;
	}


	public void setImage(byte[] image) {
		this.image = image;
	}


	public int hashCode()
	{
		return (community.getId()+this.path).hashCode();
	}
	
	@Override
	public boolean equals(Object obj) {
		CommunityFile communityFile = (CommunityFile)obj;
		return (community.getId()+this.path).equals(communityFile.community.getId()+communityFile.path);
	}


	public Set<Entry<Long, Chunk>> getChunks() {

		return chunks.entrySet();
	}


	public void updateChunk(long totalOffset, boolean primary, CommunityMemberDTO communityMember, long chunkSize) {
		Chunk chunk = chunks.get(totalOffset);
		if(chunk == null) {
			chunk = new Chunk();
			chunks.put(totalOffset, chunk);
		}
		chunk.totalOffset = totalOffset;
		chunk.chunkSize = chunkSize;
		if(primary) {
			chunk.primaryHost = communityMember;
		} else {
			chunk.redundantHost = communityMember;
		}		
	}


	public Map<Long, Chunk> getChunksMap() {
		return chunks;
	}
}
